package com.wibo.account;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.URI;

import com.wibo.common.FileDbHelper;
import com.wibo.common.Utility;

import weibo4android.Comment;
import weibo4android.Emotion;
import weibo4android.Status;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.ImageItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.LocationListener;

public class SendWeiboActivity extends Activity implements OnClickListener {

	private static final String SAVE_PREFERENCE = "SAVE_PREFERENCE";
	private static final String WEIBO_TEXT = "weiboText";
	private static final String IMAGE_PATH = "imagePath";

	private LinearLayout mMainBackground;
	private ImageView mSendBntView;
	private ImageView mBackBntView;
	private EditText mWeiboText;
	private TextView mUserName;

	private ImageView mImageBntView;
	private ImageView mGpsImageView;
	private ImageView mGotGpsImageView;
	private ProgressBar mGettingLocationBar;
	private ImageView mCameraImageView;
	private ImageView mAtImageView;
	private Uri mImageUri = null;
	private Uri mCameraImageUri = null;
	private String mCameraImagePath = "";
	private ImageView mImageView;
	private ImageView mDeleteImageView;

	private LinearLayout mDeleteTextLayout;
	private TextView mLeftTextCount;
	private double mLeftCount = 140;

	CUserManager mUserManager = null;
	protected FileDbHelper mDbHelper = null;
	private int mWeiboType = 1;
	private long mWeiboId;
	private long mCommentId;

	private String mRootUserName = null;
	private String mRootWeiboText = null;
	public static final String SEND_WEIBO_TYPE = "Weibo_type";
	public static final int SEND_NEW_WEIBO = 1;
	public static final int REPLY_COMMENT = 2;
	public static final int TRANSMIT_WEIBO = 3;
	public static final int COMMENT_COMMENT = 4;

	// reply_comment
	private TextView mCommentText;
	private LinearLayout mCommentLayout;
	private ImageView mSendWeiboCheckOn;
	private ImageView mSendWeiboCheckOff;
	private boolean mIsCheck = false;

	// transmit
	private LinearLayout mTransmitLayout;

	private LinearLayout mEmotionsLayout;
	private ImageView mEmotionsBntView;

	private GridView mEmotionsGirdView;
	private EmotionsParser mParser;

	private boolean mbRunning = false;

	public static final String EmotionStrings[] = { "[呵呵]", "[嘻嘻]", "[哈哈]",
			"[爱你]", "[晕]", "[泪]", "[馋嘴]", "[抓狂]", "[哼]", /* "[抱抱]", */"[可爱]",
			"[怒]", "[汗]", "[困]", "[害羞]", "[睡觉]", "[钱]", "[偷笑]", "[酷]", "[衰]",
			"[吃惊]", "[闭嘴]", "[鄙视]", "[挖鼻屎]", "[花心]", "[鼓掌]", "[失望]", "[思考]",
			"[生病]", "[亲亲]", "[怒骂]", "[太开心]", "[懒得理你]", "[右哼哼]", "[左哼哼]", "[嘘]",
			"[委屈]", "[吐]", "[可怜]", "[打哈气]", "[顶]", "[疑问]", "[握手]", "[耶]",
			"[good]", "[弱]", "[不要]", "[ok]", "[赞]", "[来]", "[蛋糕]", "[心]",
			"[伤心]", "[钟]", "[猪头]", "[话筒]", "[月亮]", "[下雨]", "[太阳]", "[蜡烛]",
			"[风扇]", "[男孩儿]", "[女孩儿]", "[围观]", "[威武]", "[给力]", "[神马]", "[浮云]",
			"[奥特曼]", "[兔子]", "[熊猫]", "[飞机]", "[orz]", "[调戏]", "[乐乐]", "[欢欢]",
			"[囧]"
	/*
	 * "[失望]", "[挖鼻屎]", "[黑线]", "[花心]", "[可爱]", "[吐]", "[委屈]", "[思考]", "[哈哈]",
	 * "[嘘]", "[右哼哼]", "[左哼哼]", "[疑问]", "[阴险]", "[爱你]", "[馋嘴]", "[顶]", "[钱]",
	 * "[嘻嘻]", "[汗]", "[呵呵]", "[睡觉]", "[困]", "[害羞]", "[悲伤]", "[鄙视]", "[抱抱]",
	 * "[拜拜]", "[怒]", "[吃惊]", "[闭嘴]", "[泪]", "[偷笑]", "[哼]", "[晕]", "[衰]",
	 * "[抓狂]", "[愤怒]", "[感冒]", "[鼓掌]", "[酷]", "[来]", "[good]", "[haha]", "[不要]",
	 * "[ok]", "[拳头]", "[弱]", "[握手]", "[赞]", "[耶]", "[最差]", "[右抱抱]", "[左抱抱]",
	 * "[粉红丝带]", "[心]", "[围脖]", "[温暖帽子]", "[手套]", "[红包]", "[喜]", "[礼物]", "[蛋糕]",
	 * "[钻戒]", "[钻石]", "[大巴]", "[飞机]", "[自行车]", "[汽车]", "[手机]", "[照相机]", "[药]",
	 * "[电脑]", "[手纸]", "[落叶]", "[圣诞树]", "[圣诞帽]", "[圣诞老人]", "[圣诞铃铛]", "[圣诞袜]",
	 * "[康乃馨]", "[图片]", "[六芒星]", "[地球一小时]", "[植树节]", "[粉蛋糕]", "[糖果]", "[万圣节]",
	 * "[火炬]", "[酒壶]", "[月饼]", "[满月]", "[巧克力]", "[脚印]", "[酒]", "[狗]", "[工作]",
	 * "[档案]", "[叶子]", "[钢琴]", "[印迹]", "[钟]", "[茶]", "[西瓜]", "[雨伞]", "[电视机]",
	 * "[电话]", "[太阳]", "[星]", "[哨子]", "[话筒]", "[音乐]", "[电影]", "[月亮]", "[唱歌]",
	 * "[冰棍]", "[房子]", "[帽子]", "[足球]", "[鲜花]", "[花]", "[风扇]", "[干杯]", "[咖啡]",
	 * "[兔子]", "[神马]", "[浮云]", "[给力]", "[萌]", "[鸭梨]", "[熊猫]", "[互粉]", "[织]",
	 * "[围观]", "[扔鸡蛋]", "[奥特曼]", "[威武]", "[伤心]", "[热吻]", "[囧]", "[orz]", "[宅]",
	 * "[小丑]", "[帅]", "[猪头]", "[实习]", "[骷髅]", "[便便]", "[雪人]", "[黄牌]", "[红牌]",
	 * "[跳舞花]", "[礼花]", "[打针]", "[叹号]", "[问号]", "[句号]", "[逗号]", "[闪]", "[啦啦]",
	 * "[吼吼]", "[庆祝]", "[嘿]"
	 */};
	public static final int Emotions[] = { R.drawable.smile, R.drawable.tooth,
			R.drawable.laugh, R.drawable.love, R.drawable.dizzy,
			R.drawable.sad, R.drawable.cz_org, R.drawable.crazy,
			R.drawable.hate, R.drawable.tz_org, R.drawable.angry,
			R.drawable.sweat, R.drawable.sleepy, R.drawable.shame_org,
			R.drawable.sleep_org, R.drawable.money_org, R.drawable.hei_org,
			R.drawable.cool_org, R.drawable.cry, R.drawable.cj_org,
			R.drawable.bz_org, R.drawable.bs2_org, R.drawable.kbs_org,
			R.drawable.hs_org, R.drawable.gz_org, R.drawable.sw_org,
			R.drawable.sk_org, R.drawable.sb_org, R.drawable.qq_org,
			R.drawable.nm_org, R.drawable.mb_org, R.drawable.ldln_org,
			R.drawable.yhh_org, R.drawable.zhh_org, R.drawable.x_org,
			R.drawable.wq_org, R.drawable.t_org, R.drawable.kl_org,
			R.drawable.k_org, R.drawable.d_org, R.drawable.yw_org,
			R.drawable.ws_org, R.drawable.ye_org, R.drawable.good_org,
			R.drawable.sad_org, R.drawable.no_org, R.drawable.ok_org,
			R.drawable.z2_org, R.drawable.come_org, R.drawable.cake,
			R.drawable.heart, R.drawable.unheart, R.drawable.clock_org,
			R.drawable.pig, R.drawable.m_org, R.drawable.moon, R.drawable.rain,
			R.drawable.sun, R.drawable.lazu_org, R.drawable.fan,
			R.drawable.kissgirl_org, R.drawable.kissboy_org, R.drawable.wg_org,
			R.drawable.vw_org, R.drawable.geili_org, R.drawable.horse2_org,
			R.drawable.fuyun_org, R.drawable.otm_org, R.drawable.rabbit_org,
			R.drawable.panda_org, R.drawable.travel_org, R.drawable.orz1_thumb,
			R.drawable.tiaoxi_thumb, R.drawable.guanbuzhao_thumb,
			R.drawable.liaobuqi_thumb, R.drawable.j_thumb };
	public static final int ACTIVITY_GET_IMAGE = 1;
	public static final int CASE_CAMERA = 0;

	public static final String TAG = "SendWeiboActivity";

	private static Weibo mWeibo = null;
	private static OAuthConstant mAuthConstant = null;

	private static final int SEND_WEIBO_FINISH = 1;
	private static final int SEND_WEIBO_CANCEL = 2;
	private static final int SEND_WEIBO_ERROR = -1;

	private static final int SEND_COMMENT_FINISH = 3;
	private static final int SEND_COMMENT_CANCEL = 4;
	private static final int SEND_COMMENT_ERROR = -3;

	private static final int SENT_TRANS_FINISH = 5;
	private static final int SENT_TRANS_CANCEL = 6;
	private static final int SENT_TRANS_ERROR = -5;

	private static final int GET_LOCATION_FINISH = 7;
	private static final int GET_LOCATION_CANCEL = 8;
	private static final int GET_LOCATION_ERROR = -7;

	private static final int GET_USER_LIST_FINISH = 9;
	private static final int GET_USER_LIST_CANCEL = 10;
	private static final int GET_USER_LIST_ERROR = -9;

	private Thread mThread = null;
	private ProgressDialog mWaitDialog = null;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (!mbRunning) {

				Log.e(TAG, "stop by not running flag!");
				return;
			}

			switch (msg.what) {
			case SEND_WEIBO_FINISH:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this,
						getString(R.string.sendSuc), Toast.LENGTH_SHORT).show();
				finish();
				break;
			case SEND_WEIBO_ERROR:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			case SEND_WEIBO_CANCEL:
				mWaitDialog.dismiss();
				break;
			case SEND_COMMENT_FINISH:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this,
						getString(R.string.sendSuc), Toast.LENGTH_SHORT).show();
				finish();
				break;
			case SEND_COMMENT_ERROR:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				break;
			case SEND_COMMENT_CANCEL:
				mWaitDialog.dismiss();
				break;
			case SENT_TRANS_FINISH:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this,
						getString(R.string.sendSuc), Toast.LENGTH_SHORT).show();
				finish();
				break;
			case SENT_TRANS_ERROR:
				mWaitDialog.dismiss();
				Toast.makeText(SendWeiboActivity.this,
						getString(R.string.sendFailed), Toast.LENGTH_SHORT)
						.show();
				break;
			case SENT_TRANS_CANCEL:
				mWaitDialog.dismiss();
				break;
			case GET_LOCATION_FINISH:
				mGettingLocationBar.setVisibility(ProgressBar.GONE);
				mGpsImageView.setVisibility(ImageView.GONE);
				mGotGpsImageView.setVisibility(ImageView.VISIBLE);
				releaseLocationManager();

				if (mWeiboText.getText().length() > 0)
					mSendBntView.setEnabled(true);
				break;
			case GET_LOCATION_ERROR:
				mGettingLocationBar.setVisibility(ProgressBar.GONE);
				releaseLocationManager();

				if (mWeiboText.getText().length() > 0)
					mSendBntView.setEnabled(true);
				break;
			case GET_LOCATION_CANCEL:
				mGettingLocationBar.setVisibility(ProgressBar.GONE);
				releaseLocationManager();

				if (mWeiboText.getText().length() > 0)
					mSendBntView.setEnabled(true);
				break;
			case GET_USER_LIST_FINISH:
				mWaitGettingUserDialog.hide();
				showUserListDialog();
				break;
			case GET_USER_LIST_CANCEL:
				if (mGetUserListThread != null && mGetUserListThread.isAlive()) {
					mGetUserListThread.interrupt();
					mGetUserListThread = null;
				}

				mWaitGettingUserDialog.hide();

				break;
			case GET_USER_LIST_ERROR:
				mWaitGettingUserDialog.hide();
				Toast.makeText(SendWeiboActivity.this, (String) msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			super.handleMessage(msg);
		}

	};

	private void sendMessage(int what, Object obj) {

		Message msg = mHandler.obtainMessage(what, obj);
		mHandler.sendMessage(msg);
	}
	
	private int getMySkin() {
		int skin = mUserManager.getMySkin();
		switch (skin) {
		case 0:
			return R.layout.sendweibo;
		case 1:
			return R.layout.sendweibo_2;
		default:
			return R.layout.sendweibo;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	
		mbRunning = true;
		mUserManager = CUserManager.getInstance(this);
		
		setContentView(getMySkin());
		
		if (mAuthConstant == null)
			mAuthConstant = OAuthConstant.getInstance();

		if (mWeibo == null)
			mWeibo = mAuthConstant.getWeibo();

		mWaitDialog = Utility.getWaitDialog(SendWeiboActivity.this,
				getString(R.string.WaitTip));

		if (mWaitGettingUserDialog == null) {
			mWaitGettingUserDialog = Utility
					.getWaitDialog(SendWeiboActivity.this,
							getString(R.string.gettingUserList));
		}
		mWaitGettingUserDialog
				.setOnKeyListener(new DialogInterface.OnKeyListener() {

					@Override
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						if (mGetUserListThread != null
								&& mGetUserListThread.isAlive()) {
							mGetUserListThread.interrupt();
							mGetUserListThread = null;
						}
						mWaitGettingUserDialog.hide();
						return false;
					}
				});

		mMainBackground = (LinearLayout) findViewById(R.id.mainBackground);
		mWeiboText = (EditText) findViewById(R.id.weiboText);
		mWeiboText.setOnClickListener(this);
		mWeiboText.setFocusableInTouchMode(true);
		mWeiboText.requestFocus();

		mSendBntView = (ImageView) findViewById(R.id.sendWeiboBnt);
		mBackBntView = (ImageView) findViewById(R.id.backToMain);
		mSendBntView.setOnClickListener(this);
		mBackBntView.setOnClickListener(this);

		mUserName = (TextView) findViewById(R.id.name);

		mUserName.setOnClickListener(this);

		if (mWeiboText.getText().length() > 0) {
			mSendBntView.setEnabled(true);
		} else {
			mSendBntView.setEnabled(false);
		}

		mImageBntView = (ImageView) findViewById(R.id.imageImage);
		mImageBntView.setOnClickListener(this);

		mEmotionsLayout = (LinearLayout) findViewById(R.id.emotionsLayout);
		mEmotionsBntView = (ImageView) findViewById(R.id.emotionImage);
		mEmotionsBntView.setOnClickListener(this);

		mGpsImageView = (ImageView) findViewById(R.id.gpsImage);
		mCameraImageView = (ImageView) findViewById(R.id.cameraImage);
		mAtImageView = (ImageView) findViewById(R.id.atImage);
		mGpsImageView.setOnClickListener(this);
		mCameraImageView.setOnClickListener(this);
		mAtImageView.setOnClickListener(this);

		mDeleteTextLayout = (LinearLayout) findViewById(R.id.deleteTextLayout);
		mDeleteTextLayout.setOnClickListener(this);

		mLeftTextCount = (TextView) findViewById(R.id.leftTextcount);

		TextWatcher watcher1 = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				mLeftCount = 140;
				String text = mWeiboText.getText().toString();
				double textCount = Utility.getWeiboTextCount(text);
				mLeftCount -= textCount;

				int leftCount = (int) mLeftCount;

				if (leftCount < mLeftCount && mLeftCount > 0) {
					mLeftCount -= 0.5;
				} else if (leftCount > mLeftCount && mLeftCount < 0) {
					mLeftCount -= 0.5;
				}

				mLeftTextCount.setText(String.valueOf((int) mLeftCount));
				if (mLeftCount < 0) {
					mLeftTextCount.setTextColor(getResources().getColor(
							R.color.red));
				} else {
					mLeftTextCount.setTextColor(getResources().getColor(
							R.color.sky_blue));
				}
				if (mWeiboType == SEND_NEW_WEIBO) {
					SharedPreferences preferences = getSharedPreferences(
							SAVE_PREFERENCE, 0);
					SharedPreferences.Editor editor = preferences.edit();
					editor.putString(WEIBO_TEXT, text.length() == 0 ? null
							: text);
					String path = null;
					if (mImageUri != null) {
						path = mImageUri.toString();
					} else if (mCameraImageUri != null) {
						path = mCameraImageUri.toString();
					}
					editor.putString(IMAGE_PATH, path);
					editor.commit();
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		};

		mWeiboText.addTextChangedListener(watcher1);

		mParser = new EmotionsParser(this);

		mEmotionsGirdView = (GridView) findViewById(R.id.gridview);

		mGotGpsImageView = (ImageView) findViewById(R.id.gotgpsImage);
		mGotGpsImageView.setOnClickListener(this);

		mGettingLocationBar = (ProgressBar) findViewById(R.id.gettingLocation);

		ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < EmotionStrings.length && i < Emotions.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", Emotions[i]);// 添加图像资源的ID
			// map.put("Text", EmotionStrings[i]);
			lstImageItem.add(map);
		}
		// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
		SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
				lstImageItem,// 数据来源
				R.layout.emotionsitem,// night_item的XML实现

				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage" },

				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemImage });
		// 添加并且显示
		mEmotionsGirdView.setAdapter(saImageItems);
		// 添加消息处理
		mEmotionsGirdView.setOnItemClickListener(new ItemClickListener());

		TextWatcher watcher = new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (mWeiboText.getText().length() > 0) {
					mSendBntView.setEnabled(true);
				} else {
					mSendBntView.setEnabled(false);
				}

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {

			}
		};

		mWeiboText.addTextChangedListener(watcher);

		if (mDbHelper == null)
			mDbHelper = new FileDbHelper(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mWeiboType = extras.getInt(SendWeiboActivity.SEND_WEIBO_TYPE);

			switch (mWeiboType) {
			case SEND_NEW_WEIBO:
			case REPLY_COMMENT:
			case TRANSMIT_WEIBO:
				mWeiboId = extras.getLong("weiboId");
				mCommentId = -1;
				// mOriginal =
				// (WeiboSerializable)extras.getSerializable("WeiboStatus");

				if (mWeiboId > 0) {
					if (TRANSMIT_WEIBO == mWeiboType) {
						mRootWeiboText = extras.getString("rootText");
						mRootUserName = extras.getString("rootUsername");
						if (mRootWeiboText == null) {
							mRootWeiboText = extras.getString("text");
							mRootUserName = extras.getString("username");
						} else {
							String temp = extras.getString("text");
							;
							if (temp.length() > 40) {
								temp = temp.substring(0, 40) + "...";
							}
							String name = extras.getString("username");
							mWeiboText.setText("//@" + name + ":" + temp);
							mWeiboText.setSelection(0);
						}
					} else {
						mRootWeiboText = extras.getString("text");
						mRootUserName = extras.getString("username");
					}

				}

				// try {
				// mDbHelper.open();
				// Cursor cursor = mDbHelper.getWeiboListData(mWeiboId);
				// cursor.moveToFirst();
				// if (cursor.getCount() > 0) {
				// final int weibo_text =
				// cursor.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_WEIBO_TEXT);
				// final int username =
				// cursor.getColumnIndexOrThrow(FileDbHelper.WEIBO_LIST_USERNAME);
				// mRootUserName = cursor.getString(username);
				// mRootWeiboText = cursor.getString(weibo_text);
				// }else{
				// mRootUserName = null;
				// mRootWeiboText = null;
				// }
				// } catch (Exception e) {
				// e.printStackTrace();
				// } finally {
				// mDbHelper.close();
				// }

				break;
			case COMMENT_COMMENT:
				mCommentId = extras.getLong("commentId");
				mWeiboId = extras.getLong("weiboId");
				;

				if (mCommentId > 0 && mWeiboId > 0) {
					mRootUserName = extras.getString("username");
					mRootWeiboText = extras.getString("text");
				}
				break;
			}

		}

		switch (mWeiboType) {
		case SEND_NEW_WEIBO:
			sendNewWeibo();
			break;
		case REPLY_COMMENT:
			replyComment(mWeiboId);
			break;
		case TRANSMIT_WEIBO:
			transmitWeibo(mWeiboId);
			break;
		case COMMENT_COMMENT:
			if (mRootUserName != null && mRootWeiboText != null
					&& mCommentId > 0 && mWeiboId > 0) {
				commentComment(mCommentId);
			}
			break;
		}
	}

	private void sendNewWeibo() {
		setTitle(getString(R.string.sendWeibo));
		TextPaint tp = mUserName.getPaint();
		tp.setFakeBoldText(true);
		mUserName.setText(mUserManager.getAccountUser().getName());
		mImageView = (ImageView) findViewById(R.id.image);
		mImageView.setVisibility(ImageView.GONE);
		mImageView.setOnClickListener(this);
		mDeleteImageView = (ImageView) findViewById(R.id.deleteImage);
		mDeleteImageView.setVisibility(ImageView.GONE);
		mDeleteImageView.setOnClickListener(this);

		final SharedPreferences preferences = getSharedPreferences(
				SAVE_PREFERENCE, 0);
		final String weiboText = preferences.getString(WEIBO_TEXT, null);
		final String path = preferences.getString(IMAGE_PATH, null);
		if (weiboText != null || path != null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(getString(R.string.lastWeibo));
			builder.setPositiveButton(getString(R.string.sure),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							if (weiboText != null) {
								mWeiboText.setText(mParser.replace(weiboText,
										20, 20));
								mWeiboText.setSelection(weiboText.length());
							}

							if (path != null) {
								mImageUri = Uri.parse(path);

								try {
									if (mImageUri != null) {
										ContentResolver resolver = getContentResolver();
										mBitmap = BitmapFactory
												.decodeStream(resolver
														.openInputStream(mImageUri));

										if (mBitmap != null) {
											mImageView.setImageBitmap(mBitmap);
											mImageView
													.setVisibility(ImageView.VISIBLE);
											mDeleteImageView
													.setVisibility(ImageView.VISIBLE);
										}

										mCameraImageUri = null;
										mCameraImagePath = "";
									}
								} catch (FileNotFoundException e) {
									mImageUri = null;
									e.printStackTrace();
								}
							}
						}

					});
			builder.setNegativeButton(getString(R.string.cancel),
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							SharedPreferences.Editor editor = preferences
									.edit();
							editor.putString(WEIBO_TEXT, null);
							editor.putString(IMAGE_PATH, null);
							editor.commit();
						}

					});
			builder.show();
		}
	}

	private void replyComment(long weiboId) {
		// reply
		mImageBntView.setVisibility(ImageView.GONE);
		mUserName.setText(getString(R.string.commentweibo));
		setTitle(mUserManager.getAccountUser().getName());
		mCommentText = (TextView) findViewById(R.id.friendCommentText);
		if (mRootUserName != null && mRootWeiboText != null) {
			mCommentText.setVisibility(TextView.VISIBLE);
			mCommentText.setText(mRootUserName + ": " + mRootWeiboText);
		}

		mCommentLayout = (LinearLayout) findViewById(R.id.commentAndSend);
		mCommentLayout.setVisibility(LinearLayout.VISIBLE);
		mSendWeiboCheckOn = (ImageView) findViewById(R.id.commentAndSendCheckOn);
		mSendWeiboCheckOff = (ImageView) findViewById(R.id.commentAndSendCheckOff);
		mSendWeiboCheckOn.setOnClickListener(this);
		mSendWeiboCheckOff.setOnClickListener(this);

		mGpsImageView.setVisibility(ImageView.GONE);
		mCameraImageView.setVisibility(ImageView.GONE);
	}

	private void transmitWeibo(long weiboId) {
		mImageBntView.setVisibility(ImageView.GONE);
		mUserName.setText(getString(R.string.transmitweibo));
		setTitle(mUserManager.getAccountUser().getName());
		mCommentText = (TextView) findViewById(R.id.friendCommentText);
		if (mRootUserName != null && mRootWeiboText != null) {
			mCommentText.setVisibility(TextView.VISIBLE);
			mCommentText.setText(mRootUserName + ": " + mRootWeiboText);
		}
		mTransmitLayout = (LinearLayout) findViewById(R.id.transmiatAweibo);
		mTransmitLayout.setVisibility(LinearLayout.VISIBLE);
		mSendWeiboCheckOn = (ImageView) findViewById(R.id.transmiatAweiboCheckOn);
		mSendWeiboCheckOff = (ImageView) findViewById(R.id.transmiatAweiboCheckOff);
		mSendWeiboCheckOn.setOnClickListener(this);
		mSendWeiboCheckOff.setOnClickListener(this);

		mGpsImageView.setVisibility(ImageView.GONE);
		mCameraImageView.setVisibility(ImageView.GONE);
	}

	private void commentComment(long commentId) {
		mImageBntView.setVisibility(ImageView.GONE);
		mUserName.setText(getString(R.string.commentComment));
		setTitle(mUserManager.getAccountUser().getName());
		mCommentText = (TextView) findViewById(R.id.friendCommentText);
		if (mRootUserName != null && mRootWeiboText != null) {
			mCommentText.setVisibility(TextView.VISIBLE);
			mCommentText.setText(mRootUserName + ": " + mRootWeiboText);
		}

		mCommentLayout = (LinearLayout) findViewById(R.id.commentAndSend);
		mCommentLayout.setVisibility(LinearLayout.VISIBLE);
		mSendWeiboCheckOn = (ImageView) findViewById(R.id.commentAndSendCheckOn);
		mSendWeiboCheckOff = (ImageView) findViewById(R.id.commentAndSendCheckOff);
		mSendWeiboCheckOn.setOnClickListener(this);
		mSendWeiboCheckOff.setOnClickListener(this);

		mGpsImageView.setVisibility(ImageView.GONE);
		mCameraImageView.setVisibility(ImageView.GONE);
	}

	// 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
				// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			// 在本例中arg2=arg3
			// HashMap<String, Object> item = (HashMap<String, Object>) arg0
			// .getItemAtPosition(arg2);
			// 显示所选Item的ItemText
			// setTitle((String)item.get("ItemText"));
			String weiboText = mWeiboText.getText().toString();
			int cursor = mWeiboText.getSelectionStart();
			mWeiboText.getText().insert(cursor, EmotionStrings[arg2]);
			weiboText = mWeiboText.getText().toString();
			mWeiboText.setText(mParser.replace(weiboText, 20, 20));
			mWeiboText.setSelection(cursor + EmotionStrings[arg2].length());
		}

	}

	private Thread mGetUserListThread = null;
	private ProgressDialog mWaitGettingUserDialog = null;

	private void getUserList() {
		mGetUserListThread = new Thread(new Runnable() {

			@Override
			public void run() {
				List<User> users = null;
				mUserList = new ArrayList<String>();

				try {
					int pos = 0;
					do {
						users = mWeibo.getFriendsStatuses(pos);
						if (users != null) {
							pos += users.size();

							if (pos == 0) {
								sendMessage(GET_USER_LIST_ERROR,
										getString(R.string.getUserListNull));
								break;
							} else {
								for (User user : users) {
									mUserList.add(user.getName());
								}
							}
						} else {
							mUserList = null;
							sendMessage(GET_USER_LIST_ERROR,
									getString(R.string.getUserListFailed));
							break;
						}

					} while (users.size() > 0);

					if (mUserList.size() > 0)
						sendMessage(GET_USER_LIST_FINISH, null);

				} catch (WeiboException e) {
					mUserList = null;
					sendMessage(GET_USER_LIST_ERROR,
							getString(R.string.getUserListFailed));
				}
			}
		});

		if (!mGetUserListThread.isAlive()) {
			mWaitGettingUserDialog.show();
			mGetUserListThread.start();
		}
	}

	private static ArrayList<String> mUserList = null;
	private ArrayList<String> mUserCheckedList = null;

	private void showUserListDialog() {
		if (mUserList == null || mUserList.size() == 0) {
			return;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(
				SendWeiboActivity.this);
		builder.setTitle(R.string.selectAtUser);
		builder.setMultiChoiceItems((String[]) mUserList
				.toArray(new String[mUserList.size()]), null,
				new DialogInterface.OnMultiChoiceClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						if (mUserCheckedList == null) {
							mUserCheckedList = new ArrayList<String>();
						}
						if (isChecked) {
							mUserCheckedList.add(mUserList.get(which));
						} else {
							for (int i = 0; i < mUserCheckedList.size(); i++) {
								if (mUserCheckedList.get(i).equalsIgnoreCase(
										mUserList.get(which))) {
									mUserCheckedList.remove(i);
									break;
								}
							}
						}
					}
				});

		builder.setPositiveButton(R.string.sure,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						if (mUserList != null && mUserList.size() > 0) {
							if (mUserCheckedList != null
									&& mUserCheckedList.size() > 0) {
								int pos = 0;
								for (int i = 0; i < mUserCheckedList.size(); i++) {

									if (i != mUserCheckedList.size() - 1) {
										pos = mWeiboText.getSelectionStart();
										mWeiboText.getText().insert(pos,
												mUserCheckedList.get(i) + " @");
									} else {
										pos = mWeiboText.getSelectionStart();
										mWeiboText.getText().insert(pos,
												mUserCheckedList.get(i) + " ");
									}
								}

								mUserCheckedList = null;
							}

						}
					}
				});

		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						mUserCheckedList = null;
					}
				});

		builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				mUserCheckedList = null;
				return false;
			}
		});

		builder.show();
	}

	private MKLocationManager mLocationManager = null;
	private BMapManager mBMapManager = null;

	private boolean isGettingLocation = false;
	private boolean isGotLocation = false;
	Location mLocation = null;

	private void getLocationInfo() {
		if (isGettingLocation) {
			return;
		}
		isGettingLocation = true;
		initBaiduMap();

		try {
			if (mLocationManager != null && mBMapManager != null) {

				mLocationManager.requestLocationUpdates(locationListener);
				mBMapManager.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initBaiduMap() {
		try {
			if (mBMapManager == null) {
				// if (!android.provider.Settings.Secure
				// .isLocationProviderEnabled(getContentResolver(),
				// LocationManager.NETWORK_PROVIDER))
				// android.provider.Settings.Secure
				// .setLocationProviderEnabled(getContentResolver(),
				// LocationManager.NETWORK_PROVIDER, true);

				mBMapManager = new BMapManager(getApplication());

				mBMapManager.init("7CA0B05B8858B53EB6779C9D45E787B1352AFDDC",
						new MyGeneralListener());
				Log.v("", "Init Map");
				mLocationManager = mBMapManager.getLocationManager();
				mLocationManager
						.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 百度地图初始化的listener
	public static class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onGetPermissionState(int iError) {
			// TODO Auto-generated method stub
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {

			}
		}

	}

	// 位置监听器
	private final LocationListener locationListener = new LocationListener() {
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.i(TAG, "onStatusChanged");
		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
			sendMessage(GET_LOCATION_ERROR, null);
		}

		// 当位置变化时触发
		@Override
		public void onLocationChanged(Location location) {
			// 使用新的location更新TextView显示
			mLocation = location;
			Log.i(TAG, location.getLatitude() + "," + location.getLongitude());
			isGettingLocation = false;
			isGotLocation = true;
			sendMessage(GET_LOCATION_FINISH, null);
		}
	};

	private void releaseLocationManager() {
		Log.v(TAG, "release called");
		try {
			if (mLocationManager != null) {
				mLocationManager.removeUpdates(locationListener);
				mLocationManager = null;

			}
			if (mBMapManager != null) {
				mBMapManager.stop();
				mBMapManager.destroy();
				mBMapManager = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// public static final int IMAGE_SIZE_SMALL = 50000;
	// public static final int IMAGE_SIZE_MID = 200000;
	// public static final int IMAGE_SIZE_LARGE = 2000000;
	private int mImageSize = 50;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		menu.add(0, 0, 0, getString(R.string.imageSize));

		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		super.onMenuItemSelected(featureId, item);
		switch (item.getItemId()) {
		case 0:
			showImageQualityDialog();
			break;
		}
		return false;
	}

	private void showImageQualityDialog() {
		SharedPreferences settings = getSharedPreferences(
				WiboMainActivity.USER_INFO, 0);
		mImageSize = settings.getInt(WiboMainActivity.IMAGE_QUALITY, 50);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.imageSize);

		LinearLayout layout = new LinearLayout(this);
		layout.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		layout.setOrientation(LinearLayout.VERTICAL);
		final TextView tv = new TextView(this);
		tv.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		tv.setTextColor(getResources().getColor(R.color.blue));
		tv.setText(getString(R.string.imageSize2) + String.valueOf(mImageSize)
				+ "%");

		SeekBar seekBar = new SeekBar(this);
		seekBar.setMax(100);

		seekBar.setLayoutParams(new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		seekBar.setProgress(mImageSize);

		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				mImageSize = progress;
				tv.setText(getString(R.string.imageSize2)
						+ String.valueOf(mImageSize) + "%");

				SharedPreferences settings = getSharedPreferences(
						WiboMainActivity.USER_INFO, 0);
				Editor editor = settings.edit();
				editor.putInt(WiboMainActivity.IMAGE_QUALITY, mImageSize);
				editor.commit();
			}
		});
		layout.addView(seekBar);

		layout.addView(tv);
		builder.setView(layout);
		// builder.setItems(SIZE_TEXT, new DialogInterface.OnClickListener() {
		//			
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// switch (which) {
		// case 0:
		// mImageSize = IMAGE_SIZE_SMALL;
		// break;
		// case 1:
		// mImageSize = IMAGE_SIZE_MID;
		// break;
		// case 2:
		// mImageSize = IMAGE_SIZE_LARGE;
		// break;
		// default:
		// mImageSize = IMAGE_SIZE_MID;
		// break;
		// }
		// }
		// });
		builder.show();
	}
	
	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if (1 != mUserManager.getMySkin()) {
			SharedPreferences settings = getSharedPreferences(WiboMainActivity.USER_INFO, 0);
			mBackgroundType = settings.getInt(WiboMainActivity.SEND_WEIBO_BACKGRROUND, 0);
			
			switch (mBackgroundType) {
			case 0:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_blue));
				break;
			case 1:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_green));
				break;
			case 2:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_pink));
				break;
			default:
				mMainBackground.setBackgroundDrawable(null);
				break;
			}
		}else{
			mMainBackground.setBackgroundDrawable(null);
			mBackgroundType = 3;
		}
		
	}

	static boolean inputOpen = true;
	private int mBackgroundType = 0;

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.name:
			if (1 == mUserManager.getMySkin()) {
				return;
			}
			mBackgroundType++;
			if (mBackgroundType > 3) {
				mBackgroundType = 0;
			}
			
			switch (mBackgroundType) {
			case 0:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_blue));
				break;
			case 1:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_green));
				break;
			case 2:
				mMainBackground.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.memo_pad_pink));
				break;
			default:
				mMainBackground.setBackgroundDrawable(null);
				break;
			}
			
			SharedPreferences settings = getSharedPreferences(WiboMainActivity.USER_INFO, 0);
			Editor editor2 = settings.edit();
			editor2.putInt(WiboMainActivity.SEND_WEIBO_BACKGRROUND, mBackgroundType);
			editor2.commit();
			break;
		case R.id.deleteTextLayout:
			if (mWeiboText.getText().length() > 0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.deleteTextTip));
				builder.setPositiveButton(getString(R.string.sure),
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								mWeiboText.setText("");
								mLeftCount = 140;
								mLeftTextCount.setText(String
										.valueOf((int) mLeftCount));
								mLeftTextCount.setTextColor(getResources()
										.getColor(R.color.sky_blue));
							}

						});
				builder.setNegativeButton(getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
							}

						});
				builder.show();
			}
			break;
		case R.id.sendWeiboBnt:
			if (!Utility.isNetworkAvailable(this)) {
				Toast.makeText(this, getString(R.string.networkFail),
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (mLeftCount < 0) {
				Toast.makeText(this, getString(R.string.maxCountText),
						Toast.LENGTH_SHORT).show();
				return;
			}

			if (mWeiboText.getText().length() > 0) {
				mWaitDialog.show();
				mThread = new Thread(new Runnable() {

					@Override
					public void run() {
						Status status = null;
						Comment comment = null;
						Status tranStatus = null;
						try {
							switch (mWeiboType) {
							case SEND_NEW_WEIBO:
								if (mBitmap != null) {
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									mBitmap.compress(Bitmap.CompressFormat.JPEG,
											mImageSize, baos);

									byte[] content = baos.toByteArray();
									
									ImageItem pic = new ImageItem("pic",
											content);
									if (mLocation != null) {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic,
												mLocation.getLatitude(),
												mLocation.getLongitude());
									} else {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic);
									}
								}/*
								if (mImageUri != null) {
									ContentResolver resolver = getContentResolver();
									Bitmap bitmap = BitmapFactory
											.decodeStream(resolver
													.openInputStream(mImageUri));
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									bitmap.compress(Bitmap.CompressFormat.JPEG,
											mImageSize, baos);

									byte[] content = baos.toByteArray();

									// byte[] content = getBytesFromInputStream(
									// resolver.openInputStream(Uri
									// .parse(mImageUri.toString())),
									// mImageSize);
									ImageItem pic = new ImageItem("pic",
											content);
									if (mLocation != null) {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic,
												mLocation.getLatitude(),
												mLocation.getLongitude());
									} else {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic);
									}

								} else if ((new File(Environment
										.getExternalStorageDirectory()
										.getAbsolutePath()
										+ mCameraImagePath).isFile())) {
									ContentResolver resolver = getContentResolver();
									Bitmap bitmap = BitmapFactory
											.decodeStream(resolver
													.openInputStream(mCameraImageUri));
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									bitmap.compress(Bitmap.CompressFormat.JPEG,
											mImageSize, baos);

									byte[] content = baos.toByteArray();
									// byte[] content = getBytesFromInputStream(
									// resolver.openInputStream(Uri
									// .parse(mCameraImageUri.toString())),
									// mImageSize);
									ImageItem pic = new ImageItem("pic",
											content);
									if (mLocation != null) {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic,
												mLocation.getLatitude(),
												mLocation.getLongitude());
									} else {
										status = mWeibo.uploadStatus(mWeiboText
												.getText().toString(), pic);
									}
								}*/ else {
									if (mLocation != null) {
										status = mWeibo.updateStatus(mWeiboText
												.getText().toString(),
												mLocation.getLatitude(),
												mLocation.getLongitude());
									} else {
										status = mWeibo.updateStatus(mWeiboText
												.getText().toString());
									}
								}
								break;
							case REPLY_COMMENT:
								comment = mWeibo.updateComment(mWeiboText
										.getText().toString(), String
										.valueOf(mWeiboId), null);

								if (mIsCheck) {
									tranStatus = mWeibo.updateStatus(mWeiboText
											.getText().toString(), mWeiboId);
								}
								break;
							case TRANSMIT_WEIBO:
								tranStatus = mWeibo.updateStatus(mWeiboText
										.getText().toString(), mWeiboId);

								if (mIsCheck/* && tranStatus != null */) {
									comment = mWeibo.updateComment(mWeiboText
											.getText().toString(), String
											.valueOf(mWeiboId), null);
								}
								break;
							case COMMENT_COMMENT:
								comment = mWeibo.updateComment(mWeiboText
										.getText().toString(), String
										.valueOf(mWeiboId), String
										.valueOf(mCommentId));
								if (mIsCheck) {
									tranStatus = mWeibo.updateStatus(mWeiboText
											.getText().toString(), mWeiboId);
								}
								break;
							}

						} catch (WeiboException e) {

							switch (mWeiboType) {
							case SEND_NEW_WEIBO:
								e.printStackTrace();
								sendMessage(SEND_WEIBO_ERROR,
										R.string.sendFailed);
								break;
							case REPLY_COMMENT:
								e.printStackTrace();
								sendMessage(SEND_COMMENT_ERROR,
										R.string.sendFailed);
								break;

							case TRANSMIT_WEIBO:
								e.printStackTrace();
								sendMessage(SENT_TRANS_ERROR,
										R.string.sendFailed);
								break;
							}
						} catch (Exception e) {
							switch (mWeiboType) {
							case SEND_NEW_WEIBO:
								e.printStackTrace();
								sendMessage(SEND_WEIBO_ERROR,
										getString(R.string.sendFailed));
								break;
							case REPLY_COMMENT:
								e.printStackTrace();
								sendMessage(SEND_COMMENT_ERROR,
										getString(R.string.sendFailed));
								break;
							case TRANSMIT_WEIBO:
								break;
							}
						}
						if (!Thread.interrupted()) {
							boolean bSuccuss = false;
							switch (mWeiboType) {
							case SEND_NEW_WEIBO:
								if (status != null && status.getText() != null) {
									Log.e("AndroidExample", status.getId()
											+ " : " + status.getText() + "  "
											+ status.getCreatedAt());
									sendMessage(SEND_WEIBO_FINISH, null);
									bSuccuss = true;
								} else {
									sendMessage(SEND_WEIBO_ERROR,
											getString(R.string.sendFailed));
								}
								break;
							case REPLY_COMMENT:
								if (comment != null
										&& comment.getText() != null) {
									Log.e("Send Comment", comment.getId()
											+ " : " + comment.getText() + "  "
											+ comment.getCreatedAt());
									sendMessage(SEND_COMMENT_FINISH, null);
								} else {
									sendMessage(SEND_COMMENT_ERROR,
											getString(R.string.sendFailed));
								}

								if (mIsCheck) {
									if (tranStatus != null
											&& tranStatus.getText() != null) {
										Log.e("Send tranStatus", tranStatus
												.getId()
												+ " : "
												+ tranStatus.getText()
												+ "  "
												+ tranStatus.getCreatedAt());
										sendMessage(SENT_TRANS_FINISH, null);
									} else {
										sendMessage(SENT_TRANS_ERROR,
												getString(R.string.sendFailed));
									}
								}
								break;
							case TRANSMIT_WEIBO:
								if (tranStatus != null
										&& tranStatus.getText() != null) {
									Log.e("Send tranStatus", tranStatus.getId()
											+ " : " + tranStatus.getText()
											+ "  " + tranStatus.getCreatedAt());
									sendMessage(SENT_TRANS_FINISH, null);
									bSuccuss = true;
								} else {
									sendMessage(SENT_TRANS_ERROR,
											getString(R.string.sendFailed));
								}

								if (mIsCheck) {
									if (comment != null
											&& comment.getText() != null) {
										Log
												.e("Send comment", comment
														.getId()
														+ " : "
														+ comment.getText()
														+ "  "
														+ comment
																.getCreatedAt());
										sendMessage(SEND_COMMENT_FINISH, null);
									} else {
										sendMessage(SEND_COMMENT_ERROR,
												getString(R.string.sendFailed));
									}
								}
								break;
							case COMMENT_COMMENT:
								if (comment != null
										&& comment.getText() != null) {
									Log.e("Send Comment", comment.getId()
											+ " : " + comment.getText() + "  "
											+ comment.getCreatedAt());
									sendMessage(SEND_COMMENT_FINISH, null);
								} else {
									sendMessage(SEND_COMMENT_ERROR,
											getString(R.string.sendFailed));
								}

								if (mIsCheck) {
									if (tranStatus != null
											&& tranStatus.getText() != null) {
										Log.e("Send tranStatus", tranStatus
												.getId()
												+ " : "
												+ tranStatus.getText()
												+ "  "
												+ tranStatus.getCreatedAt());
										sendMessage(SENT_TRANS_FINISH, null);
									} else {
										sendMessage(SENT_TRANS_ERROR,
												getString(R.string.sendFailed));
									}
								}
								break;
							}

							if (bSuccuss) {
								SharedPreferences preferences = getSharedPreferences(
										SAVE_PREFERENCE, 0);
								SharedPreferences.Editor editor = preferences
										.edit();
								editor.putString(WEIBO_TEXT, null);
								editor.putString(IMAGE_PATH, null);
								editor.commit();
								finish();
							}
						} else {
							switch (mWeiboType) {
							case SEND_NEW_WEIBO:
								sendMessage(SEND_WEIBO_ERROR,
										getString(R.string.sendFailed));
								break;
							case REPLY_COMMENT:
								sendMessage(SEND_COMMENT_ERROR,
										getString(R.string.sendFailed));
								break;
							case TRANSMIT_WEIBO:
								sendMessage(SENT_TRANS_ERROR,
										getString(R.string.sendFailed));
								break;
							}

						}
					}
				});
				mThread.start();
			}
			break;
		case R.id.backToMain:
			if (mWeiboType == SEND_NEW_WEIBO) {
				if (mWeiboText.getText().length() > 0 || mImageUri != null) {
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setTitle(getString(R.string.saveAsDraft));
					builder.setPositiveButton(getString(R.string.save),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									SharedPreferences preferences = getSharedPreferences(
											SAVE_PREFERENCE, 0);
									SharedPreferences.Editor editor = preferences
											.edit();
									editor.putString(WEIBO_TEXT, mWeiboText
											.getText().toString());
									String path = null;
									if (mImageUri != null) {
										path = mImageUri.toString();
									} else if (mCameraImageUri != null) {
										path = mCameraImageUri.toString();
									}
									editor.putString(IMAGE_PATH, path);
									editor.commit();
									finish();
								}

							});
					builder.setNegativeButton(getString(R.string.cancel),
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {
									SharedPreferences preferences = getSharedPreferences(
											SAVE_PREFERENCE, 0);
									SharedPreferences.Editor editor = preferences
											.edit();
									editor.putString(WEIBO_TEXT, null);
									editor.putString(IMAGE_PATH, null);
									editor.commit();
									finish();
								}

							});
					builder.show();
				} else {
					SharedPreferences preferences = getSharedPreferences(
							SAVE_PREFERENCE, 0);
					SharedPreferences.Editor editor = preferences.edit();
					editor.putString(WEIBO_TEXT, null);
					editor.putString(IMAGE_PATH, null);
					editor.commit();
					finish();
				}
			} else {
				finish();
			}
			break;
		case R.id.imageImage:
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(SendWeiboActivity.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

			Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/*");
			startActivityForResult(getImage, ACTIVITY_GET_IMAGE);
			break;
		case R.id.weiboText:

			// ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
			// .hideSoftInputFromWindow(SendWeiboActivity.this
			// .getCurrentFocus().getWindowToken(),
			// InputMethodManager.HIDE_NOT_ALWAYS);
			// mEmotionsLayout.setVisibility(LinearLayout.VISIBLE);
			// inputOpen = false;
			if (!inputOpen) {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.showSoftInput(mWeiboText, 0);
				mEmotionsLayout.setVisibility(LinearLayout.GONE);
				inputOpen = true;
				// mWeiboText.setSelection(mWeiboText.getText().length());
			}
			break;
		case R.id.emotionImage:

			if (inputOpen) {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(SendWeiboActivity.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				mEmotionsLayout.setVisibility(LinearLayout.VISIBLE);
				inputOpen = false;
			} else {
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.showSoftInput(mWeiboText, 0);
				mEmotionsLayout.setVisibility(LinearLayout.GONE);
				inputOpen = true;
				// mWeiboText.setSelection(mWeiboText.getText().length());
			}

			// try {
			// List<Emotion> emotionList = mWeibo.getEmotions("face", "cnname");
			// String ss = "";
			// for (Emotion emotion: emotionList){
			// // Utility
			// // .getImagePath(SendWeiboActivity.this, emotion.getUrl(),
			// "Emotions",
			// // Utility.THUMBNAIL_PIC);
			// ss += "\"" + emotion.getPhrase() + "\", ";
			// }
			// ss += "1";
			// } catch (WeiboException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			break;
		case R.id.image:
			showImageDialog();
			break;
		case R.id.deleteImage:
			mImageUri = null;

			mCameraImageUri = null;
			mCameraImagePath = "";
			if (mBitmap != null && mBitmap.isRecycled()) {
				mBitmap.recycle();
			}
			mBitmap = null;

			mImageView.setImageBitmap(null);
			mImageView.setVisibility(ImageView.GONE);
			mDeleteImageView.setVisibility(ImageView.GONE);
			break;
		case R.id.commentAndSendCheckOn:
			mSendWeiboCheckOn.setVisibility(ImageView.GONE);
			mSendWeiboCheckOff.setVisibility(ImageView.VISIBLE);
			mIsCheck = false;
			break;
		case R.id.commentAndSendCheckOff:
			mSendWeiboCheckOn.setVisibility(ImageView.VISIBLE);
			mSendWeiboCheckOff.setVisibility(ImageView.GONE);
			mIsCheck = true;
			break;
		case R.id.transmiatAweiboCheckOn:
			mSendWeiboCheckOn.setVisibility(ImageView.GONE);
			mSendWeiboCheckOff.setVisibility(ImageView.VISIBLE);
			mIsCheck = true;
			break;
		case R.id.transmiatAweiboCheckOff:
			mSendWeiboCheckOn.setVisibility(ImageView.VISIBLE);
			mSendWeiboCheckOff.setVisibility(ImageView.GONE);
			mIsCheck = false;
			break;
		case R.id.cameraImage:

			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(SendWeiboActivity.this
							.getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			boolean sdCardExit = Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED);

			File imageDir = null;
			Uri cameraImageUri = null;
			if (sdCardExit) {
				imageDir = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ "/Camera/Wibo_picture");

				if (!imageDir.exists()) {
					imageDir.mkdir();
				}
				mCameraImagePath = "/Camera/Wibo_picture/Wibo"
						+ String.valueOf(System.currentTimeMillis()) + ".jpg";
				cameraImageUri = Uri.fromFile(new File(Environment
						.getExternalStorageDirectory(), mCameraImagePath));
				intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
			} else {

			}
			// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

			startActivityForResult(intent, CASE_CAMERA);
			break;
		case R.id.atImage:
			int pos = mWeiboText.getSelectionEnd();
			mWeiboText.getText().insert(pos, " @");
			// mWeiboText.setText(mWeiboText.getText().toString() + " @");
			// mWeiboText.setSelection(mWeiboText.length());
			if (mUserList != null && mUserList.size() > 0) {
				sendMessage(GET_USER_LIST_FINISH, null);
			} else {
				getUserList();
			}

			break;
		case R.id.gpsImage:

			// if (isGotLocation){
			// mGpsImageView.setVisibility(ImageView.VISIBLE);
			// mGotGpsImageView.setVisibility(ImageView.GONE);
			// }else{
			// mGpsImageView.setVisibility(ImageView.GONE);
			// mGotGpsImageView.setVisibility(ImageView.VISIBLE);
			// }

			if (isGettingLocation) {
				sendMessage(GET_LOCATION_CANCEL, null);
			} else {
				mGettingLocationBar.setVisibility(ProgressBar.VISIBLE);
				getLocationInfo();
			}

			break;
		case R.id.gotgpsImage:
			if (isGotLocation) {
				mGpsImageView.setVisibility(ImageView.VISIBLE);
				mGotGpsImageView.setVisibility(ImageView.GONE);

				mLocation = null;
			}

			break;
		}
	}

	int ScaleTimes = 1;

	private void showImageDialog() {

		if (mBitmap == null) {
			return;
		}
		final View view = LayoutInflater.from(this).inflate(
				R.layout.imagehandle, null);
		final ImageView image = (ImageView) view
				.findViewById(R.id.sendingImage);
		ImageView btnRight = (ImageView) view.findViewById(R.id.turnRight);

		ScaleTimes = 1;

		ImageView btnLeft = (ImageView) view.findViewById(R.id.turnLeft);
		
		int width = mBitmap.getWidth();
		int height = mBitmap.getHeight();

		image.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth()
						: width);
		image.setMaxHeight(getImageHeight(width, height));
		image.setAdjustViewBounds(true);
		image.setImageBitmap(mBitmap);
		image.setVisibility(ImageView.VISIBLE);

		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int width = mBitmap.getWidth();
				int height = mBitmap.getHeight();
				
				int newWidth = width * ScaleTimes;
				int newHeight = height * ScaleTimes;
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleHeight);
				matrix.setRotate(/*5 * ScaleAngle*/90);
				Bitmap bitmap = Bitmap.createBitmap(mBitmap,
						0, 0, width, height, matrix, true);
				if(!mBitmap.isRecycled()){
					mBitmap.recycle();
				}
				mBitmap = bitmap;
//				BitmapDrawable myNewBitmapDrawable = new BitmapDrawable(
//						resizeBitmap);
//				image.setImageDrawable(myNewBitmapDrawable);
				
				width = mBitmap.getWidth();
				height = mBitmap.getHeight();

				image.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth()
								: width);
				image.setMaxHeight(getImageHeight(width, height));
				image.setImageBitmap(mBitmap);
				mImageView.setImageBitmap(mBitmap);
			}
		});
		
		btnLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int width = mBitmap.getWidth();
				int height = mBitmap.getHeight();
				
				int newWidth = width * ScaleTimes;
				int newHeight = height * ScaleTimes;
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleHeight);
				matrix.setRotate(/*5 * ScaleAngle*/-90);
				Bitmap bitmap = Bitmap.createBitmap(mBitmap,
						0, 0, width, height, matrix, true);
				if(!mBitmap.isRecycled()){
					mBitmap.recycle();
				}
				mBitmap = bitmap;
				
				width = mBitmap.getWidth();
				height = mBitmap.getHeight();

				image.setMaxWidth(width - getScreenWidth() > 0 ? getScreenWidth()
								: width);
				image.setMaxHeight(getImageHeight(width, height));
				
				image.setImageBitmap(mBitmap);
				mImageView.setImageBitmap(mBitmap);
			}
		});

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(view);
		builder.show();
	}

	public int getScreenHeight() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getHeight();
	}
	
	public int getScreenWidth() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		return display.getWidth();
	}

	private int getImageHeight(int width, int height) {
		if (width > getScreenWidth() - 20) {
			return ((getScreenWidth() - 20) * height) / width; 
		}
		
		return height;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mbRunning = false;
		if (mThread != null) {
			if (mThread.isAlive()) {
				mThread.interrupt();
			}
			mThread = null;
		}

		if (mGetUserListThread != null && mGetUserListThread.isAlive()) {
			mGetUserListThread.interrupt();
			mGetUserListThread = null;
		}

		if (mWaitDialog != null && mWaitDialog.isShowing()) {
			mWaitDialog.cancel();
		}

		if (mWaitGettingUserDialog != null
				&& mWaitGettingUserDialog.isShowing()) {
			mWaitGettingUserDialog.cancel();
		}

		Log.i(TAG, "onDestroy");
	}

	Bitmap mBitmap = null;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// newImage(data.getData());

		if (resultCode != RESULT_OK) {
			return;
		}

		if (requestCode == ACTIVITY_GET_IMAGE) {

			// 获得图片的uri
			if (data != null && data.getData() != null)
				mImageUri = data.getData();
			else
				mImageUri = null;

			try {
				if (mImageUri != null) {
					ContentResolver resolver = getContentResolver();
					if (mBitmap != null && mBitmap.isRecycled()) {
						mBitmap.recycle();
					}
					mBitmap = BitmapFactory.decodeStream(resolver
							.openInputStream(mImageUri));

					if (mBitmap != null) {
						mImageView.setImageBitmap(mBitmap);
						mImageView.setVisibility(ImageView.VISIBLE);
						mDeleteImageView.setVisibility(ImageView.VISIBLE);
					}

					mCameraImageUri = null;
					mCameraImagePath = "";
					//mBitmap = null;
				}
			} catch (FileNotFoundException e) {
				mImageUri = null;
				e.printStackTrace();
			}
		} else if (requestCode == CASE_CAMERA) {
			boolean sdCardExit = Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED);
			File imageFile = null;
			if (sdCardExit) {
				imageFile = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ mCameraImagePath);
				if (imageFile.exists()) {
					try {
						mCameraImageUri = Uri.fromFile(new File(Environment
								.getExternalStorageDirectory(),
								mCameraImagePath));
						ContentResolver resolver = getContentResolver();
						if (mBitmap != null && mBitmap.isRecycled()) {
							mBitmap.recycle();
						}
						mBitmap = BitmapFactory.decodeStream(resolver
								.openInputStream(mCameraImageUri));

						if (mBitmap != null) {
							mImageView.setImageBitmap(mBitmap);
							mImageView.setVisibility(ImageView.VISIBLE);
							mDeleteImageView.setVisibility(ImageView.VISIBLE);
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
			} else {
				if (data != null) {
					Bundle bundle = data.getExtras();
					if (mBitmap != null && mBitmap.isRecycled()) {
						mBitmap.recycle();
					}
					mBitmap = (Bitmap) bundle.get("data");

					if (mBitmap != null) {
						mImageView.setImageBitmap(mBitmap);
						mImageView.setVisibility(ImageView.VISIBLE);
						mDeleteImageView.setVisibility(ImageView.VISIBLE);
					}
				}
			}

			mImageUri = null;

			Log.v("cam.demo", "====>" + data);

		}

	}

	public static byte[] getBytesFromInputStream(InputStream is, int bufsiz)
			throws IOException {
		int total = 0;
		byte[] bytes = new byte[4096];
		ByteBuffer bb = ByteBuffer.allocate(bufsiz);

		while (true) {
			int read = is.read(bytes);
			if (read == -1)
				break;
			bb.put(bytes, 0, read);
			total += read;
		}

		byte[] content = new byte[total];
		bb.flip();
		bb.get(content, 0, total);

		return content;
	}

	@Override
	public void onBackPressed() {
		if (mWeiboType == SEND_NEW_WEIBO) {
			if (mWeiboText.getText().length() > 0 || mImageUri != null) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.saveAsDraft));
				builder.setPositiveButton(getString(R.string.save),
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								SharedPreferences preferences = getSharedPreferences(
										SAVE_PREFERENCE, 0);
								SharedPreferences.Editor editor = preferences
										.edit();
								editor.putString(WEIBO_TEXT, mWeiboText
										.getText().toString());
								String path = null;
								if (mImageUri != null) {
									path = mImageUri.toString();
								} else if (mCameraImageUri != null) {
									path = mCameraImageUri.toString();
								}
								editor.putString(IMAGE_PATH, path);
								editor.commit();
								finish();
							}

						});
				builder.setNegativeButton(getString(R.string.cancel),
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								SharedPreferences preferences = getSharedPreferences(
										SAVE_PREFERENCE, 0);
								SharedPreferences.Editor editor = preferences
										.edit();
								editor.putString(WEIBO_TEXT, null);
								editor.putString(IMAGE_PATH, null);
								editor.commit();
								finish();
							}

						});
				builder.show();
			} else {
				SharedPreferences preferences = getSharedPreferences(
						SAVE_PREFERENCE, 0);
				SharedPreferences.Editor editor = preferences.edit();
				editor.putString(WEIBO_TEXT, null);
				editor.putString(IMAGE_PATH, null);
				editor.commit();
				finish();
			}
		} else {
			finish();
		}
	}

}
